package com.nhncorp.ntaf;

import com.ibm.staf.*;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fit.FitServer;
import fit.Parse;

/**
 * @author nhn
 * @version 1.0
 * @created 04-8-2008 PM 5:40:12
 */
public class StafCmdFixture extends NtafColumnFixture {
	public String service;
	public String location;
	public String request;
	public String pattern;
	public String response;
	public int returnCode = 0;
	public StafHandleInterface handle = null;

	public StafCmdFixture() {
		// Register with STAF
		try {
			// for EasyMock
			handle = new StafHandleWrapper("NtafFitnesse");
		} catch (STAFException e) {
			e.printStackTrace();
		}
	}

	protected void finalize() throws Throwable {
		super.finalize();

		if (null != handle) {
			handle.unRegister();
		}
	}

	public void doTable(Parse table) {
		try {
			Parse sourceCell = getSourceCell(table);
			if (sourceCell == null) {
				addHelpComment(table);
			} else {
				doRows(table.parts.more);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int submit() {
		if (null == handle)
			return -1;

		// Submit a request			
		STAFResult stafResult = handle.submit2(location, service, request);

		// Unmarshall the result.
		// The result from the request is a marshalled list of strings. 
		response = convertEOL(unmarshall(stafResult.result));
		if (FitServer.hasSymbol(response)) {
			response = FitServer.getSymbol(response).toString();
		}

		returnCode = stafResult.rc;

		return returnCode;
	}

	public int submitMarshall() {
		if (null == handle)
			return -1;

		// Submit a request			
		STAFResult stafResult = handle.submit2(location, service, request);
		returnCode = stafResult.rc;

		if (stafResult.resultObj instanceof String) {
			response = stafResult.result;

			return returnCode;
		}

		Map resultMap = (Map)stafResult.resultObj;
		List returnedFileList = (List)resultMap.get("fileList");

		if (false == returnedFileList.isEmpty()) {
			Map stdoutMap = (Map)returnedFileList.get(0);
			response = (String)stdoutMap.get("data");
		}
		
		return returnCode;
	}	
	
	public String response() {
		return response;
	}

	// Regular Expression
	public String responsePattern() {
		String result = "";
		Pattern p1 = Pattern.compile(pattern);
		Matcher m1 = p1.matcher(response);
		if (m1.find())
			result += m1.group();

		return result;
	}

	// Html output return
	public String responseHtml() {
		return "<pre>" + fitnesse.wikitext.Utils.escapeHTML(response) + "</pre>";
	}	
	
	public String getErrorMessage() {
		String errorMsg = "";
		if (0 != returnCode) {
			STAFHandle handleErr = null;
			try {
				handleErr = new STAFHandle("AppFitnesse");

				if (null != handleErr) {
					STAFResult stafResultErr = handleErr.submit2(location, "HELP", "ERROR " + returnCode);

					errorMsg = unmarshall(stafResultErr.result);
					errorMsg = convertEOL(errorMsg);
				} else {
					return "Couldn't get a STAF hanlder.";
				}

			} catch (STAFException e) {
				e.printStackTrace();
				System.out.println("Error registering with STAF, RC:" + e.rc);
				return errorMsg;
			}

			try {
				handleErr.unRegister();
			} catch (STAFException e) {
				e.printStackTrace();
				System.out.println("Error unregistering with STAF, RC:" + e.rc);
				returnCode = e.rc;
			}
		}

		strErrorMsg = errorMsg;

		return errorMsg;
	}

	public String convertEOL(String str) {
		String resultStr = str;
		resultStr = resultStr.replaceAll("\r\n", "<br>");
		resultStr = resultStr.replaceAll("\r", "<br>");
		resultStr = resultStr.replaceAll("\n", "<br>");
		return resultStr;
	}

	public String unmarshall(String str) {
		STAFMarshallingContext mc = STAFMarshallingContext.unmarshall(str);
		return mc.toString();
	}


}